<?php

/**
 * 抽奖活动前段控制器
 */
class lotteryWebController extends base
{
    public $lotteryId,
           $lotteryInfo;
    //奖项扇形块数量及奖项对应转盘图片顺时针方向上扇形区域的位置，起始从1开始
    protected $prizeTurnMap = [
                'trunkNum' => 10,
                'awardMap' => [
                    '0' => [1, 3, 5, 7, 9],
                    '1' => [2],
                    '2' => [8],
                    '3' => [10],
                    '4' => [4],
                    '5' => [6]
                ]
           ];
    
    public function __construct() {
        $act = common::request('a', 'G');
        //是否在app内置浏览器中
        if (!common::isInAppWebview() && $act != 'lotteryShare') {
            //跳转至下载地址
            common::go('http://run.hupu.com/mobile');
        }
        
        $this->lotteryId = common::request('l_id', 'G');
        
        if(empty($this->lotteryId) && !is_numeric($this->lotteryId)) {
            common::go('http://run.hupu.com/mobile?r=404');
        }
        
        parent::__construct('show');
        $this->in_user();
        
        //未登录用户跳转至登录页
        if (!$this->uid && $act != 'lotteryShare') {
            common::go('joggers://login', true);
        }
        //获取活动信息
        $this->lotteryInfo = $this->_getLotteryInfo();
        
        if (empty($this->lotteryInfo)) {
            common::go('http://run.hupu.com/mobile?r=404');
        }
        
        $this->lotteryInfo['status'] = $this->_getLotteryStatus();
    }
    
    /**
     * 活动页
     */
    public function dolotteryIndex() {
        $lotteryInfo    = $this->lotteryInfo;
        //用户抽奖码信息
        $codeInfo       = $this->_getUserCodeInfo(); 
        $dateTime       = strtotime(date('Ymd'));
        $viewDatas      = [
            'lInfo'     => $lotteryInfo,
            'cInfo'     => $codeInfo,
            'dTime'     => $dateTime,
            'dNtime'    => $dateTime + 86400,
            'shareUrl'  => 'http://' . common::host() . '/lotteryWeb/lotteryShare/?l_id=' . $this->lotteryId
        ];
        $this->view->assign('viewDatas', $viewDatas);
        $this->view->display('show/lottery');
    }
    
    /**
     * 抽奖页
     */
    public function dolotteryDraw(){
        $lotteryInfo    = $this->lotteryInfo;
        //用户抽奖码信息
        $codeInfo       = $this->_getUserCodeInfo(); 
        
        if (empty($codeInfo)) {
            common::go('/lotteryWeb/lotteryindex/?l_id=' . $this->lotteryId);
        }
        
        $dateTime       = strtotime(date('Ymd'));
        $viewDatas      = [
            'lInfo'         => $lotteryInfo,
            'cInfo'         => $codeInfo,
            'dTime'         => $dateTime,
            'dNtime'        => $dateTime + 86400,
            'nTime'         => time(),
            'isLastD'       => $dateTime == strtotime(date('Ymd', $lotteryInfo['end_time'])) ? 1 : 0,
            'phone'         => $codeInfo[0]['phone'],
            'realname'      => $codeInfo[0]['realname'],
            'detail_addr'   => $codeInfo[0]['detail_addr']
        ];
        $this->view->assign('viewDatas', $viewDatas);
        $this->view->display('show/lottery-cj');
    }
    
    /**
     * 分享页
     */
    public function dolotteryShare() {
        $lotteryInfo    = $this->lotteryInfo;
        //获取活动参与人数
        $joins = $this->db->getCol('select count(distinct(u.id)) from r_activity_lottery_user u inner join r_activity_lottery_code c on u.id=c.ucid where c.lid=' . $this->lotteryId);
        //获取已发抽奖码数
        $codes = $this->db->getCol('select count(1) from  r_activity_lottery_code where lid=' . $this->lotteryId . ' and ucid<>0');
        $viewDatas = [
            'award_img' => $lotteryInfo['award_img'],
            'introduce' => $lotteryInfo['introduce'],
            'mbNum'     => $joins[0] + $lotteryInfo['init_joins'],
            'codeNum'   => $codes[0] + $lotteryInfo['init_code_provide'],
            'title'     => $lotteryInfo['title']
        ];
        $this->view->assign('viewDatas', $viewDatas);
        $this->view->display('show/lotteryShare');
    }
    
    /**
     * 抽奖码抽奖
     */
    public function dolotteryRun() {
        $code = common::request('l_code', 'G');
        
        if ($this->lotteryInfo['status'] == 0) {
            exit(json_encode(['code' => 101, 'msg' => '活动还未开始，不能抽奖', 'data' => []]));
        } else if ($this->lotteryInfo['status'] == 2) {
            exit(json_encode(['code' => 102, 'msg' => '活动已结束，不能抽奖', 'data' => []]));
        }
        
        $lPrizeInfo = $this->db->getRow('select c.* from r_activity_lottery_code c INNER JOIN r_activity_lottery_user u on c.ucid=u.id where  c.lid=' . $this->lotteryId . ' and c.code="' . $code . '" and u.uid=' . $this->uid . ' order by c.id desc limit 1');
        
        if (empty($lPrizeInfo)) {
            exit(json_encode(['code' => 1, 'msg' => '抽奖码有误，不能抽奖', 'data' => []]));
        } else {
            $dTime = strtotime(date('Ymd'));
            
            if ($lPrizeInfo['receive_time'] < $dTime) {
                exit(json_encode(['code' => 2, 'msg' => '抽奖码已过期，不能抽奖', 'data' => []]));
            } else if ($lPrizeInfo['receive_time'] >= ($dTime + 86400)) {
                exit(json_encode(['code' => 3, 'msg' => '抽奖时间未到，不能抽奖', 'data' => []]));
            } else if($lPrizeInfo['is_draw'] == 1) {
                exit(json_encode(['code' => 4, 'msg' => '已抽验证码，不能抽奖', 'data' => []]));
            }
            
            $ret = $this->db->updateRowTable('r_activity_lottery_code', ['id' => $lPrizeInfo['id'], 'is_draw' => 1, 'draw_time' => time()]);
            
            if ($ret === false) {
                exit(json_encode(['code' => 5, 'msg' => '抽奖失败，请重试', 'data' => []]));
            } else {
                $lotteryInfo = $this->lotteryInfo;
                !empty($lotteryInfo['award_rotate_map']) && $this->_setPrizeTurnMap(json_decode($lotteryInfo['award_rotate_map'], true));
                $turnParam = $this->_getDegreeDuring($lPrizeInfo['prize_level']);
                
                if (empty($lPrizeInfo['prize_level'])) { //未中奖
                    
                    if (strtotime(date('Ymd', $lotteryInfo['end_time'])) > $dTime  ) { //不是最后一天推送明天的抽奖码
                        // 是否已推送明日抽奖码
                        $tCodeGet = $this->db->getRowTable('r_activity_lottery_code', ['id'], 'lid=' . $this->lotteryId . ' and ucid=' . $lPrizeInfo['ucid'] . ' and receive_type=0 and receive_time>=' . ($dTime + 86400));
                        
                        if (empty($tCodeGet)) {
                            //获取未领取抽奖码
                            $tCodeInfo = [];
                            $tCodeInfo = $this->db->getRowTable('r_activity_lottery_code', ['id', 'code'], 'lid=' . $this->lotteryId . ' and ucid=' . $lPrizeInfo['ucid'] . ' and receive_time=0');
                            empty($tCodeInfo) && $tCodeInfo = $this->db->getRowTable('r_activity_lottery_code', ['id', 'code'], 'lid=' . $this->lotteryId . ' and ucid=0');
                            //更新抽奖码信息
                            $ret = $this->db->updateRowTable('r_activity_lottery_code', ['id' => $tCodeInfo['id'], 'receive_time' => ($dTime + 90000), 'ucid' =>  $lPrizeInfo['ucid']]);    
                            exit(json_encode(['code' => 0, 'msg' => '', 'data' => ['animateTo' => $turnParam['animateTo'], 'duration' => $turnParam['duration'], 'type' => 0, 'extra' => empty($ret) ? '' : $tCodeInfo['code']]]));  
                        }
                    }
                    
                    exit(json_encode(['code' => 0, 'msg' => '', 'data' => ['animateTo' => $turnParam['animateTo'], 'duration' => $turnParam['duration'], 'type' => 0, 'extra' => '']]));  
                    
                } else {
                    
                    if (strtotime(date('Ymd', $lotteryInfo['end_time'])) > $dTime  ) { //不是最后一天推送明天的抽奖码
                        // 是否已推送明日抽奖码
                        $tCodeGet = $this->db->getRowTable('r_activity_lottery_code', ['id'], 'lid=' . $this->lotteryId . ' and ucid=' . $lPrizeInfo['ucid'] . ' and receive_type=0 and receive_time>=' . ($dTime + 86400));
                        
                        if (empty($tCodeGet)) {
                            //获取未领取抽奖码
                            $tCodeInfo = [];
                            $tCodeInfo = $this->db->getRowTable('r_activity_lottery_code', ['id', 'code'], 'lid=' . $this->lotteryId . ' and ucid=' . $lPrizeInfo['ucid'] . ' and receive_time=0');
                            empty($tCodeInfo) && $tCodeInfo = $this->db->getRowTable('r_activity_lottery_code', ['id', 'code'], 'lid=' . $this->lotteryId . ' and ucid=0');
                            //更新抽奖码信息
                            $ret = $this->db->updateRowTable('r_activity_lottery_code', ['id' => $tCodeInfo['id'], 'receive_time' => ($dTime + 90000), 'ucid' =>  $lPrizeInfo['ucid']]); 
                        }
                    }
                    
                    $awardInfos = !empty($lotteryInfo['award_desc']) ? json_decode($lotteryInfo['award_desc'], true) : [];
                    $awardDesc = empty($awardInfos[$lPrizeInfo['prize_level'] - 1]) ? '' : $awardInfos[$lPrizeInfo['prize_level'] - 1];
                    $type = strpos($awardDesc, '##') === false ? 1 : 2;
                    exit(json_encode(['code' => 0, 'msg' => '', 'data' => ['animateTo' => $turnParam['animateTo'], 'duration' => $turnParam['duration'], 'type' => $type, 'extra' => $awardDesc]]));  
                }
            }
        }
    }
    
    /**
     * 手机号抽奖码获取
     */
    public function dolotteryCodeRequire() {
        $phone = common::request('phone', 'G');
        
        if ($this->lotteryInfo['status'] == 0) {
            exit(json_encode(['code' => 101, 'msg' => '活动还未开始，抽奖码领取失败']));
        } else if ($this->lotteryInfo['status'] == 2) {
            exit(json_encode(['code' => 102, 'msg' => '活动已结束，抽奖码领取失败']));
        }
        
        $pCode = $this->db->getRow('select c.id cid,u.id ucid,u.uid uid from r_activity_lottery_code c INNER JOIN r_activity_lottery_user u on c.ucid=u.id where  c.lid=' . $this->lotteryId . ' and u.phone="' . $phone . '" and c.receive_time <> 0 order by c.id desc limit 1');
        $upStatus = true;
        
        if (empty($pCode)) {
            $uPInfo = $this->db->getRowTable('r_activity_lottery_user', ['id'], 'uid=' . $this->uid . ' and phone="' . $phone . '"');
            
            if (empty($uPInfo)) {
                $ret = $this->db->insertRowTable('r_activity_lottery_user', ['uid' => $this->uid, 'phone' => $phone, 'add_time' => time()]);
                
                if ($ret) {
                    $upStatus = $this->db->query('update r_activity_lottery_code set ucid=' . $ret . ',receive_time=' . time() . ' where lid=' . $this->lotteryId . ' and ucid=0 limit 1');
                } else {
                    $upStatus = false;
                }
            } else {
                //查询是否已有后台设置奖项的抽奖码
                $setRecord = $this->db->getRow('select id from r_activity_lottery_code where lid=' . $this->lotteryId . ' and ucid=' . $uPInfo['id'] . ' and receive_time=0 order by id asc limit 1');
                
                if (empty($setRecord)) {
                    $upStatus = $this->db->query('update r_activity_lottery_code set ucid=' . $uPInfo['id'] . ',receive_time=' . time() . ' where lid=' . $this->lotteryId . ' and ucid=0 limit 1');
                } else {
                    $upStatus = $this->db->query('update r_activity_lottery_code set receive_time=' . time() . ' where id=' . $setRecord['id']);
                }
            }
        } else {
            if ($pCode['uid'] != $this->uid) {
                exit(json_encode(['code' => 2, 'msg' => '该号码已被使用，请更换手机号码']));
            }
        }
        
        if($upStatus) {
            exit(json_encode(['code' => 0, 'msg' => '抽奖码领取成功']));
        } else {
            exit(json_encod(['code' => 1, '抽奖码领取失败']));
        }
    }
    
    /**
     * 分享抽奖码获取
     */
    public function dolotteryShareCode(){
        if ($this->lotteryInfo['status'] == 0) {
            exit(json_encode(['code' => 101, 'msg' => '活动还未开始，分享抽奖码领取失败']));
        } else if ($this->lotteryInfo['status'] == 2) {
            exit(json_encode(['code' => 102, 'msg' => '活动已结束，分享抽奖码领取失败']));
        }
        
        $pCode = $this->db->getRow('select c.id cid,u.id ucid,u.uid uid from r_activity_lottery_code c INNER JOIN r_activity_lottery_user u on c.ucid=u.id where c.lid=' . $this->lotteryId . ' and u.uid=' . $this->uid . ' order by c.id desc limit 1');
        
        if(empty($pCode)) {
            exit(json_encode(['code' => 2, 'msg' => '分享抽奖码获取失败，您还未参加该抽奖活动']));
        } else {
            $ucid = $pCode['ucid'];
            
            //查询今天是否已获取分享抽奖码
            $dateTime = strtotime(date('Ymd'));
            $sCode = $this->db->getRowTable('r_activity_lottery_code', ['id'], 'lid=' . $this->lotteryId . ' and ucid=' . $ucid . ' and receive_type=1 and receive_time between ' . $dateTime . ' and ' . ($dateTime + 86400));
            
            if (!$sCode) {
                 //查询是否已有后台设置奖项的抽奖码
                $setRecord = $this->db->getRow('select id from r_activity_lottery_code where lid=' . $this->lotteryId . ' and ucid=' . $ucid . ' and receive_time=0 order by id asc limit 1');
                
                if (empty($setRecord)) {
                    $uret = $this->db->query('update r_activity_lottery_code set ucid=' . $ucid . ',receive_type=1,receive_time=' . time() . ' where lid=' . $this->lotteryId . ' and ucid=0 limit 1');
                } else {
                    $uret = $this->db->query('update r_activity_lottery_code set ucid=' . $ucid . ',receive_type=1,receive_time=' . time() . ' where id=' . $setRecord['id']);
                }
                
                if ($uret === false) {
                    exit(json_encode(['code' => '1', 'msg' => '分享抽奖码获取失败']));
                } else {
                    exit(json_encode(['code' => '0', 'msg' => '分享抽奖码获取成功']));
                }
            } else {
                exit(json_encode(['code' => '3', 'msg' => '亲，今天已领过分享抽奖码了哦']));
            }
        }
    }
    
    /**
     * 更新用户资料
     */
    public function dolotteryUserUpdate() {
        $uName  = common::request('uname', 'P');
        $uPhone = common::request('uphone', 'P');
        $uAddr  = common::request('uaddr', 'P');
        $ret = $this->db->update('update r_activity_lottery_user set realname="' . $uName . '",detail_addr="' . $uAddr . '" where uid=' . $this->uid . ' and phone="' . $uPhone . '"');
        
        if ($ret === false) {
            exit(json_encode(['code' => 1, 'msg' => '资料更新失败']));
        } else {
            exit(json_encode(['code' => 0, 'msg' => '资料更新成功']));
        }
    }
    
    /**
     * 中奖用户列表
     */
    public function dolotteryPrizeList() {
        $lotteryInfo    = $this->lotteryInfo;
        $awardDesc      = !empty($lotteryInfo['award_desc']) ? json_decode($lotteryInfo['award_desc'], true) : [];
        //用户抽奖码信息
        $codeInfo       = $this->_getUserCodeInfo();
        $prizeList      = [];
        //中奖用户信息
        if (!empty($awardDesc)) {
            $prizeUsers     = $this->_getPrizeList();

            if (!empty($prizeUsers)) {
                foreach ($prizeUsers as $pk => $pv) {
                    $award = $awardDesc[$pv['prize_level'] - 1];
                    
                    if (($pos = strpos($award, '##')) !== false) {
                        $prizeList[] = substr($pv['phone'], 0, 3) . '****' . substr($pv['phone'], 7) . '抽中' . substr($award, 0, $pos);
                    } else {
                        $prizeList[] = substr($pv['phone'], 0, 3) . '****' . substr($pv['phone'], 7) . '抽中' . $award;
                    }
                }
            }
        }
        
        echo empty($prizeList) ? '' : implode('&nbsp;&nbsp;&nbsp;', $prizeList);
        exit;
    }
    
    /**
     * 获取抽奖活动信息
     */
    protected function _getLotteryInfo() {
        return $this->db->getRowTable('r_activity_lottery', [], 'id=' . $this->lotteryId);
    }
    
    /**
     * 获取中奖用户信息
     */
    protected function _getPrizeList() {
        $sql = 'select c.prize_level,u.phone from r_activity_lottery_code c inner join r_activity_lottery_user u on c.ucid=u.id where c.lid=' . $this->lotteryId . ' and c.is_draw=1 and c.prize_level>0 order by c.prize_level asc limit 50';
        
        $ret =  $this->db->getAll($sql);
        shuffle($ret);
        return $ret;
    }


    /**
     * 用户活动抽奖码信息
     */
    protected function _getUserCodeInfo() {
        $sql = 'select c.code,c.prize_level,c.receive_type,c.receive_time,c.is_draw,u.phone,u.realname,u.detail_addr from r_activity_lottery_code c inner join r_activity_lottery_user u on c.ucid=u.id where c.lid=' . $this->lotteryId . ' and u.uid=' . $this->uid . ' and c.receive_time <> 0 order by c.id asc';
        
        return $this->db->getAll($sql);
    }
    
    /**
     * 设置奖项与转盘对应位置
     * @param array $map 奖项转盘对应关系数组
     */
    protected function _setPrizeTurnMap($map = []) {
        if (!empty($map)) {
            $this->prizeTurnMap = $map;
        }
    }
    
    /**
     * 通过奖项获取抽奖转盘旋转的度数(一圈360)和时间
     * 
     * @param numeric $prizeLevel 奖项等级
     * @param numeric $circleNum 圈数
     * @param numeric $circleTime 每圈转动时间(毫秒)
     * @return array 度数和转动时间数组 
     */
    protected function _getDegreeDuring($prizeLevel, $circleNum = 8, $circleTime = 800) {
        $datas = [];
        $chunkIndex = $this->prizeTurnMap['awardMap'][$prizeLevel];
        $indexNum = count($chunkIndex);
        
        if ($indexNum > 1) {
            $datas['animateTo'] = $circleNum * 360 + (360 / $this->prizeTurnMap['trunkNum'] * $chunkIndex[rand(0, $indexNum - 1)]);
        } else {
            $datas['animateTo'] = $circleNum * 360 + (360 / $this->prizeTurnMap['trunkNum'] * $chunkIndex[0]); 
        }
        
        $datas['duration']  = $circleNum * $circleTime + ceil(($datas['animateTo'] % 360) * 800 / 360 );
        return $datas;
    }
    
    /**
     * 获取活动状态
     */
    private function _getLotteryStatus() {
        //活动状态判断
        $nTime = time();
        
        if ($nTime < $this->lotteryInfo['start_time']) { //未开始
            return 0;
        } else if ($nTime >= $this->lotteryInfo['start_time'] && $nTime <= $this->lotteryInfo['end_time']) { //已开始
            return 1;
        } else { //已结束
            return 2;
        }
    }
}